import os
import sys

from adbutils import device
from xhs import device_manager
from xhs import db_queue

import winsound

# 必须在PyQt6导入前设置！
if getattr(sys, 'frozen', False):
    # 解决Windows 10 DLL加载问题
    os.environ["QT_PLUGIN_PATH"] = os.path.join(
        sys._MEIPASS, "PyQt6", "Qt6", "plugins"
    )
    # 添加系统路径避免DLL查找失败
    sys.path.append(sys._MEIPASS)

from PyQt6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QTextEdit, QFrame, QScrollArea,
    QTableWidget, QTableWidgetItem, QHeaderView, QDialog, QLabel, QLineEdit, QMessageBox, QFormLayout
)
from PyQt6.QtGui import QColor
# from PyQt6.QtCore import QObject

from xhs.db_queue import data_device_delete, data_device_set_status, data_device_set_app
from xhs.ui_signal import ui_signal
from xhs import config, wifi

DEFAULT_CONFIG = {
    "system": config.system,
    "mongo_url": config.mongo_url,
    "mango_db": config.mango_db,
    "mango_source": config.mango_source,
    "mango_send": config.mango_send,
    "data_time_limit": config.data_time_limit,
    "data_count_limit": config.data_count_limit,
    "data_interval": config.data_interval,
    "device_scan_sleep": config.device_scan_sleep,
    "message": config.message,
    "app_start_sleep": config.app_start_sleep,
    "app_other_sleep": config.app_other_sleep
}


# 日志信号机制：其他线程可安全写入日志
# class LogEmitter(QObject):
#     log_signal = pyqtSignal(str)
#
# log_emitter = LogEmitter()

class ConfigDialog(QDialog):
    def __init__(self, config, save_callback):
        super().__init__()
        self.setWindowTitle("当前配置（重启生效）配置文件位置 [exe根目录]\_internal\config\config.yaml")
        self.setMinimumWidth(600)  # 增大窗口宽度

        self.config = config
        self.save_callback = save_callback
        self.layout = QFormLayout()

        self.inputs = {}

        for key, value in config.items():
            if isinstance(value, list):
                # 针对列表，生成多个 QLineEdit
                self.inputs[key] = []
                for i, item in enumerate(value):
                    edit = QTextEdit(str(item))
                    self.inputs[key].append(edit)
                    self.layout.addRow(QLabel(f"{key}[{i}]"), edit)
            else:
                edit = QLineEdit(str(value))
                self.inputs[key] = edit
                self.layout.addRow(QLabel(key), edit)

        self.setLayout(self.layout)

    def save_config(self):
        for key, widget in self.inputs.items():
            val = widget.text()
            try:
                # 尝试转 int
                self.config[key] = int(val)
            except:
                self.config[key] = val
        self.save_callback(self.config)
        self.accept()


class DeviceManagerUI(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("本ADB学习工具仅用于学习研究，用户使用需自行承担风险，因使用导致的法律风险等，作者不承担责任。使用即视为同意本声明。")

        self.resize(1600, 800)

        self.config = self.load_config()

        # 主布局
        main_layout = QVBoxLayout()

        # 设备表格
        self.table = QTableWidget()
        self.table.setColumnCount(11)
        self.table.setHorizontalHeaderLabels(
            ["手机名称", "手机id", "品牌", "型号", "系统版本", "主副", "已发送次数", "是否在线", "是否启用", "操作",
             "备注"])
        # 关键设置：列宽策略（必须先设置这个）
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.Fixed)  # 先固定所有列
        header.setSectionResizeMode(9, QHeaderView.ResizeMode.Interactive)  # 操作列可交互调整

        # 设置各列宽度
        self.table.setColumnWidth(0, 120)  # 手机名称
        self.table.setColumnWidth(1, 150)  # 手机id
        self.table.setColumnWidth(2, 80)  # 品牌
        self.table.setColumnWidth(3, 100)  # 型号
        self.table.setColumnWidth(4, 100)  # 系统版本
        self.table.setColumnWidth(5, 60)  # 主副
        self.table.setColumnWidth(6, 80)  # 已发送次数
        self.table.setColumnWidth(7, 80)  # 是否在线
        self.table.setColumnWidth(8, 80)  # 是否启用
        self.table.setColumnWidth(9, 300)  # 操作列 - 加宽到400像素
        self.table.setColumnWidth(10, 300)  # 备注

        # 允许用户手动调整列宽
        header.setSectionResizeMode(9, QHeaderView.ResizeMode.Interactive)

        self.table.setFixedHeight(900)  # 设置为固定  像素高度
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setWidget(self.table)
        main_layout.addWidget(scroll_area)  # 替换原来的 main_layout.addWidget(self.table)

        # 按钮行
        button_layout = QHBoxLayout()
        self.config_btn = QPushButton("扫描usb设备")
        self.config_btn.clicked.connect(self.scan_device_usb)
        self.config_btn.clicked.connect(lambda: self.log("扫描usb设备"))
        button_layout.addWidget(self.config_btn)

        self.config_btn = QPushButton("扫描wifi设备")
        self.config_btn.clicked.connect(self.scan_device_wifi)
        self.config_btn.clicked.connect(lambda: self.log("扫描wifi设备"))
        button_layout.addWidget(self.config_btn)

        self.config_btn = QPushButton("查看配置")
        self.config_btn.clicked.connect(self.open_config_dialog)
        self.config_btn.clicked.connect(lambda: self.log("打开配置界面"))
        button_layout.addWidget(self.config_btn)

        self.wifi_btn = QPushButton("设备安装wifi（新设备需要安装一下才可以连接wifi）")
        self.wifi_btn.clicked.connect(self.open_wifi_dialog)
        # self.wifi_btn.clicked.connect(lambda: self.log("建立wifi连接"))
        button_layout.addWidget(self.wifi_btn)

        self.close_all_btn = QPushButton("全关闭")
        self.close_all_btn.clicked.connect(self.close_all)
        button_layout.addWidget(self.close_all_btn)

        self.on_button1_all_btn = QPushButton("全切换主")
        self.on_button1_all_btn.clicked.connect(self.on_button1_all)
        button_layout.addWidget(self.on_button1_all_btn)

        button_layout.addStretch()
        main_layout.addLayout(button_layout)

        # 日志框
        self.log_output = QTextEdit()
        self.log_output.setReadOnly(True)
        self.log_output.setPlaceholderText("系统日志...")
        main_layout.addWidget(self.log_output, stretch=0)

        self.setLayout(main_layout)
        # log_emitter.log_signal.connect(self.append_log)

        ui_signal.set_devices_signal.connect(self.set_devices)
        # self.table.setColumnWidth(0, 100)
        # self.table.setColumnWidth(1, 150)
        # self.table.setColumnWidth(2, 150)
        # self.table.setColumnWidth(3, 150)
        # self.table.setColumnWidth(4, 150)
        # self.table.setColumnWidth(5, 150)
        # self.table.setColumnWidth(6, 150)
        # self.table.setColumnWidth(7, 150)  # 操作按钮列
        # self.table.setColumnWidth(8, 400)  # 操作按钮列
        ui_signal.set_log.connect(self.append_log)
        # 加载初始设备列表（模拟）
        # self.set_devices([
        #     {"device_id": "002d0ec00407", "brand": "Xiaomi", "model": "Redmi 7A", "version": "Android 11"},
        # ])

    def set_devices(self, device_list):
        self.table.setRowCount(len(device_list))
        for row, dev in enumerate(device_list):
            self.table.setItem(row, 0, QTableWidgetItem(dev["device_name"]))
            self.table.setItem(row, 1, QTableWidgetItem(dev["device_id"]))
            self.table.setItem(row, 2, QTableWidgetItem(dev["brand"]))
            self.table.setItem(row, 3, QTableWidgetItem(dev["model"]))
            self.table.setItem(row, 4, QTableWidgetItem(dev["version"]))

            app_str = "主" if dev["app"] == "1" else "副"
            item_app = QTableWidgetItem(app_str)

            # 设置不同颜色
            if app_str == "主":
                item_app.setBackground(QColor(200, 255, 200))
            else:
                item_app.setBackground(QColor(255, 200, 200))

            self.table.setItem(row, 5, item_app)
            self.table.setItem(row, 6, QTableWidgetItem(str(dev["count"])))

            # self.table.setItem(row, 5, QTableWidgetItem(dev["status"]))

            # 设置值
            status = dev["status"]
            item = QTableWidgetItem(status)
            self.table.setItem(row, 7, item)
            # 设置整行颜色
            if status == "在线":
                color = QColor(200, 255, 200)  # 淡绿色
            elif status == "离线":
                color = QColor(255, 200, 200)  # 淡红色
            else:
                color = QColor(255, 255, 255)  # 白色（默认）
            item.setBackground(color)

            # 设置值
            status = dev["open_status"]
            item = QTableWidgetItem(status)
            self.table.setItem(row, 8, item)
            # 设置整行颜色
            if status == "开启":
                color = QColor(200, 255, 200)  # 淡绿色
            elif status == "关闭":
                color = QColor(255, 200, 200)  # 淡红色
            else:
                color = QColor(255, 255, 255)  # 白色（默认）
            item.setBackground(color)

            open_status = "关闭" if dev["open_status"] == "开启" else "开启"
            btn_status = QPushButton(open_status)
            btn_status.clicked.connect(
                lambda _, d_id=dev["device_id"], status=open_status: self.toggle_status_factory(d_id, status)
            )
            # 加入同一个 HBoxLayout
            hbox = QHBoxLayout()
            hbox.addWidget(btn_status)
            # 状态按钮（开启/关闭）
            if dev["open_status"] == "关闭":

                btn1 = QPushButton("主")
                btn2 = QPushButton("副")

                # 都设置为可选中（Checkable）
                btn1.setCheckable(True)
                btn2.setCheckable(True)

                # 设置样式（统一设置）
                # style = """
                #     QPushButton {
                #         background-color: #6c757d;
                #         color: white;
                #         border: none;
                #         padding: 6px 12px;
                #         border-radius: 6px;
                #     }
                #     QPushButton:hover {
                #         background-color: #5a6268;
                #     }
                #     QPushButton:checked {
                #         background-color: #007BFF;
                #         color: white;
                #     }
                # """
                # btn1.setStyleSheet(style)
                # btn2.setStyleSheet(style)

                # 设置选中状态
                if app_str == "主":
                    btn1.setChecked(True)
                    btn2.setChecked(False)
                else:
                    btn1.setChecked(False)
                    btn2.setChecked(True)

                # 绑定点击事件
                btn1.clicked.connect(
                    lambda _, d_id=dev["device_id"]: self.on_button1_clicked(d_id)
                )
                btn2.clicked.connect(
                    lambda _, d_id=dev["device_id"]: self.on_button2_clicked(d_id)
                )

                # 加入布局
                hbox.addWidget(btn1)
                hbox.addWidget(btn2)

                # 删除按钮
                btn_del = QPushButton("删")
                btn_del.clicked.connect(lambda _, d_id=dev["device_id"]: self.delete_device_factory(d_id))
                hbox.addWidget(btn_del)
            # 修改备注
            btn_note = QPushButton("修改备注")
            btn_note.setFixedWidth(50)  # 设置固定宽度
            btn_note.setStyleSheet("""
                        QPushButton {
                            background-color: #6c757d;
                            color: white;
                            border: none;
                            padding: 2px;
                            border-radius: 3px;
                        }
                        QPushButton:hover {
                            background-color: #5a6268;
                        }
                    """)
            btn_note.clicked.connect(lambda _, dev=dev: self.edit_note(dev))
            hbox.addWidget(btn_note)
            hbox.setContentsMargins(0, 0, 0, 0)
            hbox.setSpacing(5)

            container = QFrame()
            container.setLayout(hbox)
            self.table.setCellWidget(row, 9, container)

            self.table.setItem(row, 10, QTableWidgetItem(dev.get("note", "")))  # 不存在时返回空字符串

    def edit_note(self, device_data):
        """打开备注编辑对话框"""
        dialog = NoteEditDialog(device_data["device_id"], device_data["device_name"], device_data.get("note", ""))
        if dialog.exec() == QDialog.DialogCode.Accepted:
            new_note = dialog.get_note()
            try:
                # 调用数据库方法保存备注
                db_queue.data_device_set_note(device_data["device_id"], new_note)
                self.log(f"设备 {device_data['device_id']} 备注已更新")
            except Exception as e:
                self.log(f"保存备注失败: {str(e)}")
                QMessageBox.warning(self, "错误", f"保存备注失败: {str(e)}")

    def handle_device_button(self, device_id):
        self.log(f"点击操作按钮: {device_id}")
        # TODO: 暂停或恢复逻辑在此实现

    def on_button1_clicked(self, device_id: str):
        data_device_set_app(device_id, "1")

    def on_button2_clicked(self, device_id: str):
        data_device_set_app(device_id, "2")

    def toggle_status_factory(self, device_id: str, new_status: str):
        """返回一个函数，用于切换开启/关闭状态"""
        data_device_set_status(device_id, new_status)
        # 立刻更新界面中该设备的“是否启用”列颜色和文本
        row_count = self.table.rowCount()
        for row in range(row_count):
            device_id_item = self.table.item(row, 1)  # 第2列是“手机id”
            if device_id_item and device_id_item.text() == device_id:
                # 更新“是否启用”列文本
                status_item = self.table.item(row, 8)
                if status_item:
                    status_item.setText(new_status)
                    if new_status == "开启":
                        status_item.setBackground(QColor(200, 255, 200))
                    elif new_status == "关闭":
                        status_item.setBackground(QColor(255, 200, 200))
                    else:
                        status_item.setBackground(QColor(255, 255, 255))
                break
        # QMessageBox.information(self, "操作成功", "开启关闭成功")

    def close_all(self):
        row_count = self.table.rowCount()
        for row in range(row_count):
            status_item = self.table.item(row, 8)  # 第9列是“是否启用”
            device_id_item = self.table.item(row, 1)  # 第2列是“手机id”
            if status_item and status_item.text() == "开启":
                device_id = device_id_item.text()
                data_device_set_status(device_id, "关闭")
        QMessageBox.information(self, "操作成功", "已关闭所有设备")

    # def on_button1_all(self):
    #     row_count = self.table.rowCount()
    #     for row in range(row_count):
    #         status_item = self.table.item(row, 8)  # 第9列是“是否启用”
    #         app_item = self.table.item(row, 5)  # 第6列是“是否启用”
    #         device_id_item = self.table.item(row, 1)  # 第2列是“手机id”
    #         if status_item and status_item.text() == "关闭" and app_item and app_item.text() == "2":
    #             device_id = device_id_item.text()
    #             data_device_set_app(device_id, "1")
    #     QMessageBox.information(self, "操作成功", "已切换所有设备（只切换已关闭的）")

    def on_button1_all(self):
        row_count = self.table.rowCount()
        updated_devices = 0  # 记录成功更新的设备数

        for row in range(row_count):
            status_item = self.table.item(row, 8)  # 第9列是“是否启用”
            app_item = self.table.item(row, 5)  # 第6列是“是否启用”
            device_id_item = self.table.item(row, 1)  # 第2列是“手机id”

            # 检查是否所有需要的 item 都存在
            if not (status_item and app_item and device_id_item):
                continue  # 跳过无效行

            status = status_item.text()
            app_status = app_item.text()
            device_id = device_id_item.text()

            if status == "关闭" and app_status == "副":
                data_device_set_app(device_id, "1")
                updated_devices += 1

        if updated_devices > 0:
            QMessageBox.information(self, "操作成功", f"已切换 {updated_devices} 个设备（已开启的不切换）")
        else:
            QMessageBox.warning(self, "无操作", "没有符合条件的设备可切换")

    def delete_device_factory(self, device_id: str):
        data_device_delete(device_id)
        QMessageBox.information(self, "操作成功", "删除成功")

    def open_config_dialog(self):
        dialog = ConfigDialog(self.config.copy(), self.save_config)
        dialog.exec()

    def open_wifi_dialog(self):
        wifi.connect_all_devices();
        QMessageBox.information(self, "操作成功", "安装成功，手机要点击确定！！！！")

    def scan_device_usb(self):
        device_manager.base_connect_type = "usb"
        QMessageBox.information(self, "操作成功", "扫描usb设备，有延迟稍等")

    def scan_device_wifi(self):
        device_manager.base_connect_type = "wifi"
        QMessageBox.information(self, "操作成功", "扫描wifi设备，有延迟稍等")

    def save_config(self, new_config):
        self.config = new_config
        self.log("配置已保存")

    def load_config(self):
        return DEFAULT_CONFIG

    def append_log(self, msg):
        self.log_output.append(msg)

    def log(self, msg):
        # log_emitter.log_signal.emit(msg)
        ui_signal.set_log.emit(msg)


class NoteEditDialog(QDialog):
    def __init__(self, device_id, device_name, current_note=""):
        super().__init__()
        self.setWindowTitle(f"编辑备注 - {device_name}")
        self.setFixedSize(400, 200)

        layout = QVBoxLayout()

        self.note_edit = QTextEdit(current_note)
        self.note_edit.setPlaceholderText("请输入备注内容...")
        layout.addWidget(self.note_edit)

        btn_box = QHBoxLayout()
        save_btn = QPushButton("保存")
        save_btn.clicked.connect(self.accept)
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        btn_box.addWidget(save_btn)
        btn_box.addWidget(cancel_btn)

        layout.addLayout(btn_box)
        self.setLayout(layout)

    def get_note(self):
        return self.note_edit.toPlainText()
